在C++中,通訊是一種 流動,而非靜態的儲存事件。 iostream 函式庫使用了一個 多型層次結構 其中特化類別如 ifstream (檔案)和 istringstream (記憶體)繼承自 istream。這使得 串流繼承:為基底串流設計的函數可透明地處理來自任何來源的資料。
不可複製的限制
串流代表與硬體之間獨一無二且具狀態的連接。為防止多個物件爭奪同一個檔案指標或主控台緩衝區,IO 物件 無法被複製或賦值。嘗試撰寫如下程式碼 ofstream out1, out2; out1 = out2; 將導致編譯錯誤。因此,IO 物件必須以 非常數參考傳遞。
順序橋樑
雖然串流提供介面, 順序容器 (vector, list) 提供記憶體。輸入的資料通常會被組織成這些容器,選擇 vector 以追求速度,或選擇 list 以支援彈性插入。
main.py
TERMINALbash — 80x24
> Ready. Click "Run" to execute.
>
QUESTION 1
What causes the termination of
while (cin >> i)?The stream reaching a value of 0.
Encountering end-of-file (EOF) or an invalid input type.
The buffer becoming full.
A semicolon in the input stream.
✅ Correct!
Correct. The expression evaluates to the stream itself, which in a boolean context returns false if the stream's failbit or eofbit is set.❌ Incorrect
The while loop terminates when the stream state becomes invalid, such as entering a character when an integer was expected.QUESTION 2
Identify the error:
ofstream out1, out2; out1 = out2;Logic error: Files cannot have the same name.
Syntax error: Stream assignment is prohibited.
Runtime error: Buffer overflow.
No error; this is standard C++ usage.
✅ Correct!
Stream objects are non-copyable and non-assignable to prevent ambiguous hardware management.❌ Incorrect
C++ deletes the copy constructor and assignment operator for IO classes.QUESTION 3
How should an
istream be passed to a function that reads from it?By value (e.g., void func(istream is))
By const reference (e.g., void func(const istream &is))
By non-const reference (e.g., void func(istream &is))
As a pointer to a const object.
✅ Correct!
Reading from a stream changes its internal state (e.g., position pointers), so it must be a non-const reference.❌ Incorrect
Since streams are non-copyable, 'by value' is impossible. Since reading modifies the stream, 'const reference' is invalid.QUESTION 4
What is the primary flaw in this loop?
while (iter1 < iter2) where iter is a list<int>::iterator?Lists only support
!= comparison for iterators.The loop will result in an infinite recursion.
List iterators must be decremented.
You cannot compare iterators of the same container.
✅ Correct!
Correct! Because lists are not stored contiguously, the < operator is not defined; use != instead.❌ Incorrect
The < operator is only defined for random-access iterators (like vector or deque).QUESTION 5
Why would you call
is.clear() before returning an istream& from a function?To delete all data within the stream.
To reset the error state (like EOF) so the caller can continue using it.
To flush the output buffer.
To close the associated file handle.
✅ Correct!
Once a stream hits EOF, it remains in an error state. clear() resets the state bits.❌ Incorrect
clear() affects the state flags, not the data contents or file connection.Case Study: The polymorphic Logging & Storage System
Managing Stream IO and Sequential Containers
You are designing a system that reads user input and stores it. You need a function that can read from either the standard console (cin) or a file, stores every word individually, and returns the stream to a healthy state for the next component.
Q
1. Implement Exercise 8.1: Write the C++ function that reads an istream until EOF, prints the content, and resets the stream.
Solution:
The function would look like this:
The function would look like this:
istream& readAndReset(istream &is) {
string val;
while (is >> val) {
cout << val << endl;
}
is.clear(); // Essential to reset EOF state
return is;
}Q
2. Provide a usage guide for when to select: vector, list, deque, map, and set.
Solution:
vector: Best for fast random access and adding elements at the end. list: Best for frequent insertions/deletions anywhere in the container. deque: Best for insertions/deletions at both ends (queues). map: Best for key-value pairs where fast lookups by key are needed. set: Best for maintaining a sorted collection of unique elements.
vector: Best for fast random access and adding elements at the end. list: Best for frequent insertions/deletions anywhere in the container. deque: Best for insertions/deletions at both ends (queues). map: Best for key-value pairs where fast lookups by key are needed. set: Best for maintaining a sorted collection of unique elements.
Q
3. Exercise 8.5: How would you modify a program to store each word of a file into a vector of strings?
Solution:
By using the extraction operator
By using the extraction operator
>>, which naturally stops at whitespace: string word;
while (inputFile >> word) {
vec.push_back(word);
} This differs from getline(), which reads whole lines including spaces.